package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserServiceImpl
 * Package: com.sky.service.impl
 * Description:
 *
 * @Author 八云
 * @Create 2025/3/21 22:18
 * @Version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    // 微信服务接口地址
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 创建一个 Map 作为请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("appid", weChatProperties.getAppid());
        requestBody.put("secret", weChatProperties.getSecret());
        requestBody.put("js_code", userLoginDTO.getCode());
        requestBody.put("grant_type", "authorization_code");
        log.info("微信登录请求体：{}", requestBody);

        // 创建 WebClient 实例
        WebClient webClient = WebClient.create();

        // 构建请求 URI
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(WX_LOGIN);
        requestBody.forEach(builder::queryParam);
        String uri = builder.toUriString();

        // 发送 GET 请求
        String json = webClient.get()
                .uri(uri)
                .retrieve()
                .bodyToMono(String.class)
                .block();
        log.info("微信登录响应体：{}", json);

        // 将字符串转换为 JSONObject
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        log.info("openid：{}", openid);

        // 判断openid是否为空，如果为空则登录失败，抛出业务异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 判断当前用户是否是新用户
        User user = userMapper.getByOpenid(openid);

        // 如果是新用户，自动完成注册
        if (user == null){
            log.info("新用户自动注册");
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }


}
